package com.bds.btcdc.web.service;

import com.bds.btcdc.web.model.UserKeys;
import com.bds.btcdc.web.model.common.UserSession;
import com.bds.btcdc.web.utils.Const;
import com.bds.btcdc.web.utils.CookieUtils;
import com.bds.btcdc.web.utils.DESUtil;
import com.bds.btcdc.web.utils.RedisUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.SerializationUtils;
import org.nutz.dao.impl.NutDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;

@Service
public class SetupService {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private NutDao dao;

    /**
     * 保存用户设置的api-keys
     */
    public boolean saveApiKeys(HttpServletRequest request, String exchange, String accessKey, String secretKey){
        Cookie cookie = CookieUtils.getCookieByName(request, Const.COOKIES_USER_KEY);
        String token = cookie.getValue();
        Charset CHARSET = Charset.forName("utf-8");
        String user_id;
        try {
            user_id = DESUtil.decrypt(token, CHARSET, Const.DESKEY);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        try {
            UserKeys keys=new UserKeys();
            keys.setUser_id(Long.parseLong(user_id));
            keys.setExchange(exchange);
            String _accessKey = DESUtil.encrypt(String.valueOf(accessKey), CHARSET, Const.DESKEY);
            String _secretKey = DESUtil.encrypt(String.valueOf(secretKey), CHARSET, Const.DESKEY);
            keys.setAccess_key(_accessKey);
            keys.setSecret_key(_secretKey);
            dao.fastInsert(keys);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
